package com.atguigu.gulimall.rocksdb.api;

import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.rocksdb.repository.KeyValueRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/rocksdb")
public class RocksApi {

    private final KeyValueRepository<String, String> rocksDB;

    public RocksApi(KeyValueRepository<String, String> rocksDB) {
        this.rocksDB = rocksDB;
    }

    @PostMapping(value = "/{key}")
    public R save(@PathVariable("key") String key, @RequestBody String value) {
        log.info("RocksApi.save");
        rocksDB.save(key, value);
        return R.ok().put("data", value);
    }

    @GetMapping(value = "/{key}")
    public R find(@PathVariable("key") String key) {
        log.info("RocksApi.find");
        String result = rocksDB.find(key);
        if (result == null) {
            log.error(BizCodeEnume.ROCKSDB_DELETE_ERROR.getMessage());
            return R.error(BizCodeEnume.ROCKSDB_DELETE_ERROR.getCode(), BizCodeEnume.ROCKSDB_DELETE_ERROR.getMessage());
        }
        return R.ok().put("data", result);
    }

    @DeleteMapping(value = "/{key}")
    public R delete(@PathVariable("key") String key) {
        log.info("RocksApi.delete");
        rocksDB.delete(key);
        return R.ok(key);
    }
}
